﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace GetEmailAttachment
{
    public static class FileHelper
    {
        /// <summary> 
        /// 将 Stream 写入文件 
        /// </summary> 
        public static void StreamToFile(Stream stream, string fileName)
        {
            // 把 Stream 转换成 byte[] 
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);

            // 把 byte[] 写入文件 
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(bytes);
            bw.Close();
            fs.Close();
        }

        /// <summary>
        /// 判断文件夹是否存在
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool DirExists(string filePath)
        {
            return Directory.Exists(filePath);
        }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="filePath"></param>
        public static void CreateFolder(string filePath)
        {
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="filePath"></param>
        public static void CreateFile(string filePath,bool IsCover=true)
        {
            System.IO.FileStream fs = null;
            try
            {
                if (!File.Exists(filePath))
                {
                    fs = System.IO.File.Create(filePath);
                    fs.Close();
                    fs.Dispose();
                }
                else if(IsCover)//覆盖
                {
                    fs = new FileStream(filePath, FileMode.Open, FileAccess.Write);
                    fs.SetLength(0);
                    fs.Close();
                    fs.Dispose();
                }
            }
            catch (Exception)
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }

        }
        public static void WriteLineToTxt(string path,string value)
        {
            FileStream fs = new FileStream(path, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(value);
            sw.Close();
            fs.Close();
        }

        /// <summary>
        /// Base64解密，采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(string result)
        {
            return DecodeBase64(Encoding.UTF8, result);
        }
        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="codeName">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(Encoding encode, string result)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }
        public static string DecodeQ(string code, string codebase)
        {

            string[] textArray1 = code.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
            byte[] buf = new byte[textArray1.Length];
            try
            {

                for (int i = 0; i < textArray1.Length; i++)
                {
                    if (textArray1[i].Trim() != string.Empty)
                    {

                        byte[] buftest = new byte[2];

                        buf[i] = (byte)int.Parse(textArray1[i].Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
                    }
                }
            }
            catch
            {
                return null;
            }
            return System.Text.Encoding.GetEncoding(codebase).GetString(buf);
        }

        public static string Decode(string sourcecode)
        {
            string ret = string.Empty;
            string[] codes;
            /*
             =?gb2312?B?ueO3orv5vfDI7bz+vLzK9bf+zvHIt8jPtaVfMjAxNzA3X0ZyZWVib3JkZXJz?= =?gb2312?Q?(IT)=5FV01.xlsx?=
             */
            int pos1;
            if ((pos1 = sourcecode.IndexOf("=?")) >= 0)       //判断是否有编码
            {
                ret = sourcecode.Substring(0, pos1);          //取出编码前的内容
                sourcecode = sourcecode.Substring(pos1).Trim();
                codes=sourcecode.Split(new[] { " " }, StringSplitOptions.None);
                //codes = Regex.Split(sourcecode, "=?", RegexOptions.IgnoreCase);
            }
            else
            {
                return sourcecode;                            //无编码直接返回
            }
            foreach (var c in codes)
            {
                if (c == "")
                    continue;
                var code = c.Trim();
                if (code.StartsWith("=?") /*&& code.EndsWith("?=")*/)
                {
                    string[] fields = code.Split('?');
                    string codebase = fields[1];
                    string codetype = fields[2];
                    string text = string.Empty;

                    if (codetype.ToLower() == "q")
                    {
                        for (int i = 0; i < fields.Length / 4; i++)
                        {
                            text += fields[i * 4 + 3];
                        }
                        //string text = msgsubj;

                        string decodeq = string.Empty;
                        while (text.Length > 0)
                        {
                            //判断编码部分是否开始
                            if (text.Substring(0, 1) == "=")
                            {
                                decodeq = text.Substring(0, 3);
                                text = text.Substring(3, text.Length - 3);
                                //当出现编码部分时，则取出连续的编码部分
                                while (text.Length > 0)
                                {
                                    if (text.Substring(0, 1) == "=")
                                    {
                                        decodeq += text.Substring(0, 3);
                                        text = text.Substring(3, text.Length - 3);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                //将连续的编码进行解码
                                ret += DecodeQ(decodeq, codebase);
                            }
                            //如果该字节没编码，则不用处理
                            else
                            {
                                ret += text.Substring(0, 1);
                                text = text.Substring(1, text.Length - 1);
                            }

                        }

                    }
                    else   //对base64编码解码
                    {
                        byte[] strbase64;
                        try
                        {
                            text = string.Empty;
                            string str = "";
                            for (int i = 0; i < fields.Length / 4; i++)
                            {
                                str += fields[i * 4 + 3];
                                if (str.EndsWith("="))
                                {
                                    try
                                    {
                                        strbase64 = Convert.FromBase64String(str);
                                        ret += System.Text.Encoding.GetEncoding(codebase).GetString(strbase64);
                                        str = "";
                                    }
                                    catch
                                    {
                                        ret += code;
                                    }
                                }
                            }

                            if (!string.IsNullOrEmpty(str))
                            {
                                try
                                {
                                    strbase64 = Convert.FromBase64String(str);
                                    ret += System.Text.Encoding.GetEncoding(codebase).GetString(strbase64);
                                    str = "";
                                }
                                catch
                                {
                                    ret += code;
                                }

                            }
                        }

                        catch
                        {
                            ret += code;
                        }
                    }
                    
                }
            }
            return ret;

        }
    }
}
